#include "LinkList_head.h"

static LinkList_t * tail = NULL;

int LinkList_head_init(LinkList_t **LinkList){
    if(*LinkList!=NULL){
        return -1;
    }
    (*LinkList) = (LinkList_t *)malloc(sizeof(LinkList_t));
    if((*LinkList)==NULL){
        LOG("LinkList create failed\n");
        return -1;
    }
    //创建头节点
    (*LinkList)->next = NULL;
    LOG("LinkList create success\n");
    return 0;
}

//头插
int LinkList_head_headinsert(LinkList_t *head,int data){
    if(head == NULL){
        return -1;
    }
    LinkList_t * p = (LinkList_t *)malloc(sizeof(LinkList_t));
    if(p==NULL){
        LOG("item create failed\n");
        return -1;
    }
    LinkList_t *q = head;
    p->data = data;
    p->next = q->next;
    head->next = p;
    return 0;
}

//尾插
int LinkList_head_tailinsert(LinkList_t *head,int data){
    if(head == NULL){
        return -1;
    }
    LinkList_t * p = (LinkList_t *)malloc(sizeof(LinkList_t));
    if(p==NULL){
        LOG("item create failed\n");
        return -1;
    }
    if(head->next == NULL){
        tail = head;
    }
    p->data = data;
    tail->next = p;
    p->next = NULL;
    tail = p;
    return 0;
}

//删除指定节点
int LinkList_head_delitem(LinkList_t *head,int index){
    if(head==NULL){
        return -1;
    }
    LinkList_t * p = head->next;
    LinkList_t * prev = head;
    int i = 0;
    while(p!=NULL){
        if(i==index){
            prev->next = p->next;
            free(p);
            p = NULL;
            break;
        }
        p = p->next;
        prev = prev ->next;
        i++;
    }
    return 0;
}

//回收链表
int LinkList_head_destory(LinkList_t * head){
    if(head==NULL){
        return -1;
    }
    LinkList_t * p = head->next;
    while (p!=NULL)
    {
        LinkList_t * q = p->next;
        free(p);
        p = q;
    }
    free(head);
    head = NULL;
    return 0;
}

int LinkList_head_select(LinkList_t *head){
    LinkList_t * p  = head->next;
    while(p!=NULL){
        printf("[%d]->",p->data);
        p = p->next;
    }
    printf("NULL\n");
    return 0;
}

